import { Button } from 'antd'
import axios from 'axios'
import React from 'react'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { isAuth } from '../../helpers/auth'
import { CartItem } from '../../helpers/cart'
import { Jwt } from '../../models/isAuth'
export interface Props {
  address: string,
  totalPrice: number,
  cart: CartItem[]
}
const Pay = ({address, totalPrice, cart}:Props) => {
  const getPayUrl = async () => {
    const response = await axios.post(`${API}/alipay`,{
        	// 支付宝接口要求的必填参数
    totalAmount: totalPrice,
    subject: "测试订单",
    body: "测试订单描述",
     // 服务器端要求的必填参数
    products: cart.map(item=>({product: item._id, count: item.count})),
		address: address,
    userId: (isAuth() as Jwt).user._id
    })
    window.location.href = response.data.result
  }
  const showButton = () => {
    return isAuth() ? <Button onClick={()=>getPayUrl()}>提交订单</Button> : <Button type="link"><Link to="/signin">登录</Link></Button>
  }
  return (
    <div>
      {
        showButton()
      }
    </div>
  )
}
export default Pay